<?php

namespace Modules\User\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\User\Entities\VipSku;
use Modules\User\Entities\VipOrder;

use Auth;
use Validator;
use ThrowException;
use DB;

class VipOrderController extends Controller
{
    // 购买vip套餐
    public function store(Request $req)
    {
		$rule = [
            'sku_id' => ['required'],
            'address_id' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $user = Auth::requireLoginUser();

        $vipSku = VipSku::getEntity([
        	'id' => $req->sku_id
        ]);

        $address = $user->addresses()->where('id', $req->address_id)->first() ?: ThrowException::Conflcit('收货地址错误');

        DB::beginTransaction();

        $skuableMaps = [
        	[
        		'skuable' => $vipSku,
        		'total' => 1
        	]
        ];

        $coupon = NULL;
        if ($req->input('coupon_id'))
            $coupon = $user->coupons()->valid()->where('id', $req->coupon_id)->first();
        $isUseRedpack = $req->input('is_use_redpack');

        $order = VipOrder::initWith($skuableMaps, $user, $address, [
            'coupon' => $coupon,
            'is_use_redpack' => $isUseRedpack,
        	'options' => [
        		'sku_id' => $vipSku->id
        	]
        ]); 

        $order->createAll();
        
        DB::commit();
        
        return $order->generateResponse();
    }
}
